package com.ad.pet.app.mall;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.mall.adapter.ServiceTilteAdapter;
import com.ad.pet.app.mall.adapter.SkuAdapter;
import com.ad.pet.app.mall.view.ServiceSkuDialog;
import com.ad.pet.common.data.utils.DensityUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.mall.ChoseOrder;
import com.ad.pet.models.remote.mall.OrderDoorInfo;
import com.ad.pet.models.remote.mall.ServiceDetail;
import com.ad.pet.models.remote.mall.SkuPirce;
import com.ad.pet.models.remote.mall.SkuProps;
import com.ad.pet.ui.FlowLayoutManager;
import com.ad.pet.ui.loopview.LoopView;
import com.ad.pet.ui.loopview.entity.LoopViewEntity;
import com.library.flowlayout.SpaceItemDecoration;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Created by liuyixiang on 2019/11/17.
 */

public class ServiceDetailActivity extends AppToolbarActivity implements ServiceDetailContracts.View {
    @BindView(R.id.relative_sku)
    RelativeLayout mRelativeSku;
    @BindView(R.id.loopView)
    LoopView loopView;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.recycelr_service)
    RecyclerView recycelrService;
    @BindView(R.id.iv_service_detail)
    WebView ivServiceDetail;
    @BindView(R.id.tv_store_connect)
    TextView tvStoreConnect;
    @BindView(R.id.tv_inshop)
    TextView tvInshop;
    @BindView(R.id.tv_indoor)
    TextView tvIndoor;
    @BindView(R.id.iv_colletion)
    ImageView ivColletion;
    @BindView(R.id.tv_collection)
    TextView tvCollection;

    @BindView(R.id.linear_collection)
    LinearLayout mLinearCollection;



    private ServiceSkuDialog serviceSkuDialog;
    private TextView btnDoorOrder;
    private TextView btnOnDoor;

    @Inject
    ServiceDetailPresenter serviceDetailPresenter;
    private String oid;
    private String sid;
    private ServiceTilteAdapter serviceTilteAdapter;
    private RecyclerView mRecyclerSku;
    private ImageView mIvDialogClose;
    private SkuAdapter mSkuAdapter;
    private ImageView mIvDialogHead;
    private TextView mTvDialogTitle;
    private TextView mTvDialogPrice;
    private TreeMap<Integer, String> mSkuMap;
    private TreeMap<Integer,String> mSkuNameMap;
    private String hasChoseSkumap="";
    private String hasCHoseSkuName="";
    private ServiceDetail mServiceDetail;
    String shopName="";
    private SkuPirce skuPirce1;
    @Inject
    RxDisposable mRxDisposable;


    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();
//        mToolbar.getRightImage().setImageResource(R.drawable.ic_shop_cart);
//        mToolbar.getRightImage().setVisibility(View.VISIBLE);
//        mToolbar.getRightImage().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
// 2019.11.1 2019.11.9 2019.11.17 2019.11.26
//            }
//        });
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_service_detail;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {


        oid = getIntent().getStringExtra(Constant.ORDER_ID);
        sid = getIntent().getStringExtra(Constant.SHIPPING_ID);
        shopName = getIntent().getStringExtra("shop_name");

        serviceTilteAdapter = new ServiceTilteAdapter(null);
        recycelrService.setLayoutManager(new FlowLayoutManager());
        recycelrService.addItemDecoration(new SpaceItemDecoration(DensityUtil.dip2px(5)));
        recycelrService.setAdapter(serviceTilteAdapter);


        serviceSkuDialog = new ServiceSkuDialog(this, R.style.custom_dialog_style);
        btnDoorOrder = serviceSkuDialog.findViewById(R.id.tv_order);
        btnOnDoor = serviceSkuDialog.findViewById(R.id.tv_door);
        mRecyclerSku = serviceSkuDialog.findViewById(R.id.recycler_sku);
        mIvDialogClose = serviceSkuDialog.findViewById(R.id.iv_close);
        mIvDialogHead = serviceSkuDialog.findViewById(R.id.iv_service);
        mTvDialogTitle = serviceSkuDialog.findViewById(R.id.tv_name);
        mTvDialogPrice = serviceSkuDialog.findViewById(R.id.tv_price);


        LinearLayoutManager linearLayoutManager112 = new LinearLayoutManager(mActivity);
        mRecyclerSku.setLayoutManager(linearLayoutManager112);
        mSkuAdapter = new SkuAdapter(null);
        mRecyclerSku.setAdapter(mSkuAdapter);

    }

    @Override
    protected void initData() {

        serviceDetailPresenter.onCreate(this);
        serviceDetailPresenter.getServiceDetail(oid, sid);
        serviceDetailPresenter.getSkuPriceDetail(oid,"");
        mSkuMap = new TreeMap<>();
        mSkuNameMap = new TreeMap<>();

    }

    @Override
    protected void initEvents() {

        tvStoreConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mServiceDetail!=null)
                {
                    DialogUtil.createDialog(mActivity, "", "是否拨打"+mServiceDetail.getShop_phone()+"?", "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            call_phone(mServiceDetail.getShop_phone());
                        }
                    }).show();
                }
            }
        });
        tvIndoor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ToastUtil.getToastUtil().showShort("敬请期待");
            }
        });
        tvInshop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceSkuDialog.show();
//                if (!hasLogin()){
//                    Navigation.goLogin(mActivity,1,1);
//                    return;
//                }
//                ChoseOrder choseOrder = new ChoseOrder(sid,skuPirce1.getSku_id(),hasCHoseSkuName,mServiceDetail.getOffservice_id(),mServiceDetail.getOffservice_name(),shopName);
//                choseOrder.setPrice(skuPirce1.getPrice());
//                Navigation.goDoorOrder(ServiceDetailActivity.this,choseOrder);
            }
        });
        mLinearCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mRelativeSku.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceSkuDialog.show();
            }
        });
        btnOnDoor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.getToastUtil().showShort("敬请期待");
            }
        });
        btnDoorOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!hasLogin()){
                    Navigation.goLogin(mActivity,1,1);
                    return;
                }
                ChoseOrder choseOrder = new ChoseOrder(sid,skuPirce1.getSku_id(),hasCHoseSkuName,mServiceDetail.getOffservice_id(),mServiceDetail.getOffservice_name(),shopName);
                choseOrder.setPrice(skuPirce1.getPrice());

                Navigation.goDoorOrder(ServiceDetailActivity.this,choseOrder);
            }
        });

        mIvDialogClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serviceSkuDialog.dismiss();
            }
        });
        mSkuAdapter.setOnSkuItemClickLinstenr(new SkuAdapter.OnSkuItemClickLinstenr() {
            @Override
            public void onSkuItemClick(int positon, int itemPosition) {

                List<SkuProps> skuProps = mSkuAdapter.getData();
                setChoseSku(positon, itemPosition, skuProps);
                serviceDetailPresenter.getSkuPriceDetail(oid,hasChoseSkumap);

                StringBuffer skuName = getStringBuffer();
                mTvDialogTitle.setText(skuName.toString());
//                Logger.e("select_sku-->" + selectSku.toString());
            }
        });

        mLinearCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!hasLogin()){
                Navigation.goLogin(mActivity,1,1);
                return;}
                if (mServiceDetail.isIs_fav()){

                    serviceDetailPresenter.cancelService(mServiceDetail.getOffservice_id(),sid);
                }else {
                    serviceDetailPresenter.addService(mServiceDetail.getOffservice_id(),sid);
                }


            }
        });

        mRxDisposable.add(RxBus.getDefault().toObservable(String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if ("close_door".equals(s)) {

                            finish();
                        }
                    }
                }));
    }

    @NonNull
    private StringBuffer getStringBuffer() {
        StringBuffer skuName = new StringBuffer();
        skuName.append(mServiceDetail.getOffservice_name());
        skuName.append(" ");
        String nskName = hasCHoseSkuName.replaceAll(",", " ");

        skuName.append(nskName);
        return skuName;
    }

    private void setChoseSku(int positon, int itemPosition, List<SkuProps> skuProps) {
        mSkuMap.put(positon, skuProps.get(positon).getValue().get(itemPosition).getSpec_id()+":"+skuProps.get(positon).getValue().get(itemPosition).getSpec_value_id());
        mSkuNameMap.put(positon,skuProps.get(positon).getValue().get(itemPosition).getName());

        StringBuffer selectSku = new StringBuffer();
        StringBuffer selectName = new StringBuffer();
        Set<Integer> set = mSkuMap.keySet();//用接口实例接口
        Iterator<Integer> iter = set.iterator();
        while (iter.hasNext()) {//遍历二次,速度慢
            int next =iter.next();
            selectSku.append(mSkuMap.get(next));
            selectSku.append(";");
            selectName.append(mSkuNameMap.get(next));
            selectName.append(",");
        }
        if (selectSku.length() != 0) {
            selectSku.delete(selectSku.length() - 1, selectSku.length());

        }
        if (selectName.length()!=0){
            selectName.delete(selectName.length()-1,selectName.length());
        }

        hasChoseSkumap= selectSku.toString();
        hasCHoseSkuName=selectName.toString();

    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void error(int code, String msg) {

    }

    @Override
    public void getServiceDetialSuccess(ServiceDetail serviceDetail) {


        mServiceDetail = serviceDetail;
        List<LoopViewEntity> loopViewEntities = new ArrayList<>();
        for (int i = 0; i < serviceDetail.getPicture_img().size(); i++) {
            loopViewEntities.add(new LoopViewEntity(serviceDetail.getPicture_img().get(i)));
        }
        loopView.setLoopData(loopViewEntities);

        tvShopName.setText(serviceDetail.getOffservice_name());
        mTvDialogTitle.setText(serviceDetail.getOffservice_name());
        tvPrice.setText("￥" + serviceDetail.getPrice());

        serviceTilteAdapter.setNewData(serviceDetail.getList());
//        ivServiceDetail.setText(Html.fromHtml(serviceDetail.getDescription(), getImageGetter(), null));
        ivServiceDetail.loadData(serviceDetail.getDescription(),"text/html", "utf-8");
        for (int i = 0; i < serviceDetail.getOffservice_spec_format().size(); i++) {
            serviceDetail.getOffservice_spec_format().get(i).getValue().get(0).setChose(true);
            for (int j = 0; j < serviceDetail.getOffservice_spec_format().get(i).getValue().size(); j++) {
                if (serviceDetail.getOffservice_spec_format().get(i).getValue().get(j).isChose()==true){
                setChoseSku(i,j,serviceDetail.getOffservice_spec_format());}
            }
        }
        StringBuffer skuName = getStringBuffer();
        mTvDialogTitle.setText(skuName.toString());
        serviceDetailPresenter.getSkuPriceDetail(oid,hasChoseSkumap);
        mSkuAdapter.setNewData(serviceDetail.getOffservice_spec_format());

        collectService(mServiceDetail.isIs_fav());
    }

    private void collectService(boolean serviceDetail) {
        if (serviceDetail){
            ivColletion.setImageResource(R.drawable.ic_service_uncollection);
            tvCollection.setText("已收藏");
        }else {
            ivColletion.setImageResource(R.drawable.ic_service_collection);
            tvCollection.setText("收藏");
        }
    }

    @Override
    public void getSkuPriceDetailSuccess(SkuPirce skuPirce) {
        skuPirce1 = skuPirce;
            mTvDialogPrice.setText("￥"+skuPirce.getPrice());
        GlideUtil.load(mActivity,skuPirce.getPicture(),mIvDialogHead);

    }

    @Override
    public void getDoorBasicInfoSuccess(OrderDoorInfo orderDoorInfo) {

    }

    @Override
    public void upDoorOrderSuccess() {

    }

    @Override
    public void addServiceSuccess() {
        ToastUtil.getToastUtil().showShort("添加收藏成功");
        mServiceDetail.setIs_fav(true);
        collectService(mServiceDetail.isIs_fav());
    }

    @Override
    public void cancelServiceSuccess() {
        ToastUtil.getToastUtil().showShort("取消收藏成功");
        mServiceDetail.setIs_fav(false);
        collectService(mServiceDetail.isIs_fav());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private Html.ImageGetter getImageGetter() {
        return new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                Drawable drawable = mActivity.getResources().getDrawable(Integer.parseInt(source));
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
                return drawable;
            }
        };
    }

    public void call_phone(String phone) {


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) this, Manifest.permission.CALL_PHONE)) {

                Toast.makeText(this, "请授权！", Toast.LENGTH_LONG).show();

                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", this.getPackageName(), null);
                intent.setData(uri);
                this.startActivity(intent);
            } else {
                ActivityCompat.requestPermissions((Activity) this, new String[]{Manifest.permission.CALL_PHONE}, 1);
            }
        } else {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + phone));
            this.startActivity(intent);
        }

    }
}
